﻿using System;
using System.Web;
using Business;
using Entity;
using Entity.Custom;
using Newtonsoft.Json;
using Utilities;

namespace FreshCms.BackEnd.Handler
{
    /// <summary>
    /// Summary description for Group
    /// </summary>
    public class Group : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        #region Declare variable for check pms
        Int32 ui = 0;
        InPms chkPms = new InPms();
        InUser CurrentUser = new InUser();
        #endregion

        public void ProcessRequest(HttpContext context)
        {
            string m = "";
            var response = new ResponseData();

            #region Get PanelId and Check Psm
            CurrentUser = InUserBusiness.GetSessionInUser();
            if (!string.IsNullOrEmpty(context.Request["ui"]))
            {
                Int32.TryParse(context.Request["ui"], out ui);
                if(ui>0)
                    chkPms = InPmsBusiness.CheckSessionPms(ui);
                if(chkPms==null)
                    chkPms = new InPms{PmsView = 0, PmsUpdate = 0, PmsDelete = 0};
            }
            #endregion



            if (context.Request.RequestType == "POST")
            {
                if (context.Request["m"] != null)
                    m = context.Request["m"];
                else
                    return;
            }
            else
            {
                if (context.Request.QueryString["m"] != null)
                    m = context.Request.QueryString["m"];
                else
                    return;
            }

            switch (m.ToLower())
            {
                case "add":
                    response = AddGroup(context);
                    break;
                case "delete":
                    response = DeleteGroup(context);
                    break;
            }

            context.Response.ContentType = "application/x-javascript";

            string callBack = context.Request["callback"];
            if (!string.IsNullOrEmpty(callBack))
            {
                context.Response.Write(callBack + "( " + JsonConvert.SerializeObject(response) + " );");
            }
            else
                context.Response.Write(JsonConvert.SerializeObject(response));
        }


        private ResponseData AddGroup(HttpContext context)
        {
            // Check Pms
            if(chkPms.PmsUpdate==0)
                return new ResponseData{Data = null, ExtData = null, Message = Constant.PmsNoUpdate, Success = false};
            
            var response = new ResponseData();
            
            if (!string.IsNullOrEmpty(context.Request["name"]) && !string.IsNullOrEmpty(context.Request["stt"]))
            {
                Int32 groupid = 0;
                if (!string.IsNullOrEmpty(context.Request["id"]))
                    Int32.TryParse(context.Request["id"], out groupid);
                string groupname = context.Request["name"];
                Int32 groupstatus = 0;
                Int32.TryParse(context.Request["stt"], out groupstatus);

                var obj = new InGroup
                {
                    GroupId = groupid,
                    GroupName = groupname,
                    GroupStatus = groupstatus
                };
                response.Data = InGroupBusiness.UpdateInGroup(obj);
                response.Message = "Call Insert OK";
                response.Success = true;

                if (groupid > 0)
                {
                    InLogBusiness.InsertInLog(new InLog
                    {
                        UserId = CurrentUser.UserId,
                        LogAction = 2,
                        Field1 = "Update nhóm người dùng thành công",
                        Field2 = "Nhóm được thay đổi thông tin: " + groupname,
                        Field3 = "",
                        LogId = 0
                    });
                }else
                {
                    InLogBusiness.InsertInLog(new InLog
                    {
                        UserId = CurrentUser.UserId,
                        LogAction = 1,
                        Field1 = "Thêm nhóm người dùng mới thành công",
                        Field2 = "Tên nhóm mới: " + groupname,
                        Field3 = "",
                        LogId = 0
                    });
                }
                
            }else
            {
                response.Data = -1;
                response.Message = "Param Name, Status not valid";
                response.Success = false;
            }

            return response;
        }

        private ResponseData DeleteGroup(HttpContext context)
        {
            // Check Pms
            if (chkPms.PmsDelete == 0)
                return new ResponseData { Data = null, ExtData = null, Message = Constant.PmsNoDelete, Success = false };
            
            var response = new ResponseData();
            if (!string.IsNullOrEmpty(context.Request["id"]))
            {
                var groupid = 0;
                Int32.TryParse(context.Request["id"], out groupid);
                if (groupid>0)
                {
                    response.Data = InGroupBusiness.DeleteInGroup(groupid);
                    response.Message = "Call Delete OK";
                    response.Success = true;
                    // log system 
                    InLogBusiness.InsertInLog(new InLog
                    {
                        UserId = CurrentUser.UserId,
                        LogAction = 0,
                        Field1 = "Xóa nhóm người dùng thành công",
                        Field2 = "ID nhóm bị xóa: " + groupid,
                        Field3 = "",
                        LogId = 0
                    });
                }else
                {
                    response.Data = groupid;
                    response.Message = "GroupId <=0";
                    response.Success = false;   
                }
            }
            else
            {
                response.Data = -1;
                response.Message = "Param not valid";
                response.Success = false;
            }
            return response;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}